package com.quinn.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @author 周汉坤
 */
public class ReadHandler {


    public static void main(String[] args) throws Exception {

        String SD = "D:\\wor\\SD.xlsx";
        String D = "D:\\wor\\D.xlsx";
        List<StaffDept> sdList = read(SD, StaffDept.class);
        List<Dept> dList = read(D, Dept.class);
        write(packageList(sdList, dList));
    }

    private static List<StaffDept> packageList(List<StaffDept> sdList, List<Dept> dList) {
        HashMap<String, Dept> codeDeptMap = new HashMap<>();
        dList.forEach(o -> codeDeptMap.put(o.getDeptCode(), o));
        dList.forEach(o -> {
            Dept curDept = codeDeptMap.get(o.getDeptCode());
            while (curDept != null) {
                if (o.getTargetDeptName() == null) {
                    o.setTargetDeptName(o.getDeptName());
                } else {
                    o.setTargetDeptName(curDept.getDeptName() + "/" + o.getTargetDeptName());
                }
                curDept = codeDeptMap.get(curDept.getParentDeptCode());
            }
        });
        sdList.forEach(o -> {
            o.setTargetDept(codeDeptMap.get(o.getDeptCode()).getTargetDeptName());
        });
        return sdList;
    }

    public static <T> List<T> read(String link, Class<T> clazz) throws FileNotFoundException {

        InputStream in = new BufferedInputStream(new FileInputStream(link));
        ExcelListener listener = new ExcelListener();
        ExcelReader excelReader = EasyExcel.read(in, clazz, listener).build();

        ReadSheet readSheet = EasyExcel.readSheet(1).build();
        readSheet.setSheetName("Sheet1");
        excelReader.read(readSheet);

        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();
        return listener.getList();

    }

    public static void write(List<StaffDept> list) {
        String fileName = "D:\\wor\\233.xlsx";

        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭

        // 如果这里想使用03 则 传入excelType参数即可

        EasyExcel.write(fileName, StaffDept.class).sheet("写入方法一").doWrite(list);
    }
}
